<template>
  <div class="list" ref="$listRef">
    <div :draggable="true" class="list-item list-item_1">12</div>
    <div :draggable="true" class="list-item list-item_2">13</div>
    <div :draggable="true" class="list-item list-item_3">14</div>
    <div :draggable="true" class="list-item list-item_4">15</div>
    <div :draggable="true" class="list-item list-item_5">16</div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'

  const sourceNode = ref<any>(null)

  onMounted(() => {
    const listDom: HTMLElement = document.querySelector('.list')!
    listDom.ondragstart = (e: DragEvent) => {
      const target = e.target as HTMLElement
      if (target) {
        setTimeout(() => {
          target.classList.add('moving')
        }, 0)
        sourceNode.value = target
        e.dataTransfer!.effectAllowed = 'move'
      }
    }

    listDom.ondragover = (e) => {
      e.preventDefault()
    }

    listDom.ondragenter = (e: DragEvent) => {
      e.preventDefault()
      const target = e.target as HTMLElement
      if (target) {
        if (target == listDom || target == sourceNode.value) {
          return
        }

        const children = Array.from(listDom.children)

        children.forEach((ele) => {
          ele.setAttribute('style', 'transition: 0.3s all ease-in-out')
        })

        const sourceIndex = children.indexOf(sourceNode.value)
        const targetIndex = children.indexOf(target)

        if (sourceIndex < targetIndex) {
          listDom.insertBefore(sourceNode.value, target.nextElementSibling)
        } else {
          listDom.insertBefore(sourceNode.value, target)
        }
      }
    }

    listDom.ondragend = (e: DragEvent) => {
      const target = e.target as HTMLElement
      if (target) {
        target.classList.remove('moving')
        const children = Array.from(listDom.children)
        const arr: unknown[] = []
        children.forEach((i) => {
          // console.log('%c [ i ]-64', 'font-size:13px; background:#788310; color:#bcc754;', i)
          arr.push(i.innerHTML)
        })

        console.log('%c [  ]-67', 'font-size:13px; background:#1c95f1; color:#60d9ff;', arr)
      }
    }
  })
</script>

<style lang="less" scoped>
  .list {
    width: 80%;
    height: 30vh;
    display: grid;
    grid-template-columns: auto;
    grid-template-rows: repeat(5, 20%);
    row-gap: 8px;
    margin-bottom: 30px;

    .list-item {
      width: 70%;
      background-color: pink;
      color: green;
      font-size: 18px;
      border-radius: 8px;
      cursor: move;
    }
    .moving {
      background: transparent;
      color: transparent;
      border: 1px dashed #ccc;
    }
  }
</style>
